package com.example.flag03;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    //    存放选项时间
    private List<String> radioList = new ArrayList<>();
    //选中的时间位置
    private int checkedIndex = 0;

    //    数据库变量
    private MyDatabaseHelper databaseHelper;
    //    MyCursorAdapter对象
    MyCursorAdapter myCursorAdapter;
    //      根view
//    private View mainView;
    //    数据库实体游标
    private Cursor cursor;
    //    flag的标题
    private String titleText;
    //    flag的计划
    private String planText;
    //    时间
    private int toYear;
    private int toMonth;
    private int toDay;
    private int fromYear=0;
    private int fromMonth=0;
    private int fromDay=0;
    //    创建日历对象
    Calendar calendar = Calendar.getInstance();
    //    展示的时间
    private int showYear = 0;
    private int showMonth;
    //    展示flag的类型
    private Boolean isOutTime = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        获取根目录的view
//        mainView= getWindow().getDecorView();

//        初始化数据
        radioList.add("ALL");

        //创建数据库的对象
        databaseHelper = new MyDatabaseHelper(this, "FlagData.dp", null, 1);
        //初始化数据库
        databaseHelper.getWritableDatabase();

        //到当前的年月日
        fromYear = calendar.get(Calendar.YEAR);
        fromMonth = calendar.get(Calendar.MONTH) + 1;
        fromDay = calendar.get(Calendar.DAY_OF_MONTH);
//        默认的终止时间
        toYear = fromYear;
        toMonth = fromMonth;
        toDay = fromDay+1;

//        获取数据库数据
        getData();


        //    选择按钮T F
        RadioGroup radioGroup = findViewById(R.id.radioGroup);
        RadioButton radioButtonT = (RadioButton) findViewById(R.id.radioT);
        RadioButton radioButtonF = (RadioButton) findViewById(R.id.radioF);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Toast.makeText(MainActivity.this, "2123131313", Toast.LENGTH_SHORT).show();
                if (radioButtonF.getId() == checkedId) {
                    isOutTime = true;
                    radioButtonT.setChecked(false);
                    radioButtonF.setChecked(true);
                } else {
                    isOutTime = false;
                    radioButtonF.setChecked(false);
                    radioButtonT.setChecked(true);
                }
                getData();
            }
        });


//        悬浮按钮
//        FloatingActionButton imageButton=(FloatingActionButton) findViewById(R.id.send);

//      查询有多少个flag即将到期（3天内）
        setTip();

//        跳转到我的界面
        ImageView mineView=(ImageView)findViewById(R.id.mine);
        mineView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到我的页面
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,mine.class);
                startActivity(intent);
            }
        });

    }

    //    这个方法在活动由不可见变为可见的时候调用。
    @Override
    protected void onStart() {
        super.onStart();
        //重新获取数据的逻辑，此处根据自己的要求回去
        getData();
        setTip();
    }

//    关闭数据库
    @Override
    protected void onDestroy() {
        if (myCursorAdapter!= null ) {
            myCursorAdapter.getCursor().close();
        }
        super.onDestroy();
    }


    //      查询有多少个flag即将到期（3天内）
    private void setTip() {
        int day=fromDay+2;
        SQLiteDatabase db = databaseHelper.getWritableDatabase();
        Cursor cursorTip = db.query("Flag", null, "signal=" +0 +" AND toDay>="+fromDay+" AND toDay<="+day +" AND toYear="+fromYear +" AND toMonth="+toMonth , null, null, null, null);
        int number = cursorTip.getCount();
        if(number>0){
            TextView textView = (TextView)findViewById(R.id.tip_text);
            textView.setText("温馨提示：即将有"+String.valueOf(number)+"个Flag过期！");
            RelativeLayout relativeLayout=(RelativeLayout)findViewById(R.id.tip_wrapper);
            relativeLayout.setVisibility(View.VISIBLE);
        }

//        取消提示
        RelativeLayout relativeLayout=(RelativeLayout)findViewById(R.id.tip_wrapper);
        ImageView imageView=(ImageView)findViewById(R.id.cancel_button);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                relativeLayout.setVisibility(View.INVISIBLE);
            }
        });

//        关闭数据库
        cursorTip.close();
    }

    //        获取数据库数据函数
    private void getData() {
//        radioList集合清空
        radioList.clear();
        radioList.add("ALL");
        SQLiteDatabase db = databaseHelper.getWritableDatabase();
//        查询数据
        /*
        table:数据库表的名称 
        columns:数据库列名称数组 写入后最后返回的Cursor中只能查到这里的列的内容 
        selection:查询条件  
        selectionArgs:查询结果  
        groupBy:分组列 
        having:分组条件 
        orderBy:排序列 
         */
//        查询数据
        if (showYear == 0) {
            if (isOutTime) {
                Toast.makeText(MainActivity.this, "1", Toast.LENGTH_SHORT).show();
                cursor = db.query("Flag", null, "signal=" + -1, null, null, null, null);
            } else if (!isOutTime) {
                Toast.makeText(MainActivity.this, "2", Toast.LENGTH_SHORT).show();
                cursor = db.query("Flag", null, "signal>" + -1 +" AND signal<"+2, null, null, null, null);
            }

        } else {
            if (isOutTime) {
                Toast.makeText(MainActivity.this, "3", Toast.LENGTH_SHORT).show();
                cursor = db.query("Flag", null, "fromYear=" + showYear + " AND fromMonth=" + showMonth + " AND signal=" + -1, null, null, null, null);
            } else if (!isOutTime) {
                Toast.makeText(MainActivity.this, "4", Toast.LENGTH_SHORT).show();
                cursor = db.query("Flag", null, "fromYear=" + showYear + " AND fromMonth=" + showMonth + " AND signal!=" + -1, null, null, null, null);
            }
        }


//        绑定主布局中的样式
        ListView listView = findViewById(R.id.listView);
        myCursorAdapter= new MyCursorAdapter(MainActivity.this, cursor, fromYear, fromMonth, fromDay, databaseHelper);
        listView.setAdapter(myCursorAdapter);

//        点击跳转到相应的页面
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListView listView1 = (ListView) parent;
                Cursor cursor1 = (Cursor) listView1.getItemAtPosition(position);

                //携带_id跳转到详情页面
                Intent intent = new Intent();
                intent.putExtra("_id", cursor1.getInt(cursor1.getColumnIndex("_id")));
                intent.putExtra("nowYear", fromYear);
                intent.putExtra("nowMonth", fromMonth);
                intent.putExtra("nowDay", fromDay);
                intent.setClass(MainActivity.this,detail.class);
                startActivity(intent);

               // Toast.makeText(MainActivity.this,""+cursor1.getInt(cursor1.getColumnIndex("_id")), Toast.LENGTH_SHORT).show();
            }
        });

//        长按删除
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                ListView listView1 = (ListView) parent;
                Cursor cursor1 = (Cursor) listView1.getItemAtPosition(position);
                String flagTitle=cursor1.getString(cursor1.getColumnIndex("flagTitle"));
                //        弹窗提示
                final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setCancelable(false);
                builder.setMessage("是否删除Flag"+flagTitle+"?");
                builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        删除记录
                    int _id=cursor1.getInt(cursor1.getColumnIndex("_id"));
                    SQLiteDatabase db = databaseHelper.getWritableDatabase();
                    db.delete("Flag","_id=?",new String[]{Integer.toString(_id)});
                    db.close();
//                    刷新
                    getData();
                    }
                });

                AlertDialog dialog = builder.create();
                dialog.show();
                return true;
            }
        });

////       查询时间列表
        Cursor cursorTime = db.query("Flag", new String[]{"timeList"}, null, null, null, null, null);
        if (cursorTime.moveToFirst()) {
            do {
                String time = cursorTime.getString(cursorTime.getColumnIndex("timeList"));
                if(time==null){
                    break;
                }
                if(!time.equals("-1")) {
                    radioList.add(time);
                }
            } while (cursorTime.moveToNext());
        }
//        关闭数据库
        if(cursorTime!=null){
            cursorTime.close();
        }
        Toast.makeText(MainActivity.this, "radioList.get(0)", Toast.LENGTH_SHORT).show();
        databaseHelper.close();
    }


    //    展示时间列表
    public void showAction(View view) {
        String[] items = radioList.toArray(new String[radioList.size()]);

        final AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.layout01);
        builder.setTitle("请选择");
        builder.setSingleChoiceItems(items, checkedIndex, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                更改展示的时间
                TextView textView = (TextView) findViewById(R.id.displayTime);
                textView.setText(items[which]);
//                赋值
                checkedIndex = which;
//                分割字符串
                if (items[which] != "ALL") {
                    String[] array = items[which].split("\\.");
                    showYear = Integer.valueOf(array[0]);
                    showMonth = Integer.valueOf(array[1]);
                } else {
                    showYear = 0;
                }

//                        提示选中
                Toast.makeText(MainActivity.this, items[which], Toast.LENGTH_SHORT).show();
                dialog.dismiss();
                //        更新数据
                getData();
            }

        });
        builder.setCancelable(true);
        AlertDialog alertDialog = builder.create();
        Window window=alertDialog.getWindow();
        WindowManager.LayoutParams params=window.getAttributes();
        params.x=10;
        params.y=100;
        params.width=200;
        params.height=800;
        window.setAttributes(params);
        alertDialog.show();
    }


    //    发布动态
    public void release(View view) {
        Toast.makeText(MainActivity.this, "" + radioList.get(0), Toast.LENGTH_SHORT).show();

        //动态加载布局文件，得到相应的View对象
        View view1 = View.inflate(this, R.layout.release, null);

        final AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.layout01);
        builder.setTitle("发表Flag");
        builder.setView(view1);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setPositiveButton("提交", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
                View view = layoutInflater.inflate(R.layout.release, null);
//                        获取相应的控件ID
                TextView title = (TextView) view1.findViewById(R.id.titleText);
                TextView plan = (TextView) view1.findViewById(R.id.planText);

//                        赋值title,plan
                titleText = title.getText().toString();
                planText = plan.getText().toString();

//                        上传数据
                sendData();


//              Toast.makeText(MainActivity.this,titleText,Toast.LENGTH_SHORT).show();
                Toast.makeText(MainActivity.this, "" + radioList.get(0), Toast.LENGTH_SHORT).show();
            }
        });

//                设置当前时间
        TextView nowTime = (TextView) view1.findViewById(R.id.nowTime);
        nowTime.setText(fromYear + "." + fromMonth + "." + fromDay);
//        设置终止时间
        TextView textView = (TextView) view1.findViewById(R.id.endTime);
        textView.setText(toYear + "." + toMonth  + "." + toDay);

//        选择终止时间
        ImageView showSelectTime = (ImageView) view1.findViewById(R.id.showSelectTime);
        showSelectTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                                textView.setText(year + "." + (month + 1) + "." + dayOfMonth);
                                toYear = year;
                                toMonth = month+1;
                                toDay = dayOfMonth;
                            }
                        }, toYear, toMonth, toDay);

                //设置起始日期和结束日期
                DatePicker datePicker = datePickerDialog.getDatePicker();
                datePicker.setMinDate(System.currentTimeMillis());
//                datePicker.setMaxDate(System.currentTimeMillis());
                datePickerDialog.show();
            }
        });

//        按钮居中
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Button positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
        Button negativeButton = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) positiveButton.getLayoutParams();
        layoutParams.weight = 10;
        positiveButton.setLayoutParams(layoutParams);
//        positiveButton.setBackground(getResources().getDrawable(R.drawable.positive_button));
        negativeButton.setLayoutParams(layoutParams);

    }

    //    上传数据
    private void sendData() {
//      上传时间列表
        String string = fromYear + "." + fromMonth;
        SQLiteDatabase db = databaseHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("flagTitle", titleText);
        values.put("flagPlan", planText);
        values.put("fromYear", fromYear);
        values.put("fromMonth", fromMonth);
        values.put("fromDay", fromDay);
        values.put("toYear", toYear);
        values.put("toMonth", toMonth);
        values.put("toDay", toDay);
        values.put("finishedYear", "0");
        values.put("finishedMonth", "0");
        values.put("finishedDay", "0");
        values.put("signal", "0");
        values.put("timeList", "-1");
        if (radioList.indexOf(string) == -1) {
            //                            不重复，添加数据
            values.put("timeList", string);
        }
        db.insert("Flag", null, values);
        databaseHelper.close();
//        更新数据
        getData();
    }

}